setup_swig_javascript_env()
include_directories(../../include ../../xcomm/include)

# Add swig module
set_property(SOURCE javascript.i PROPERTY CPLUSPLUS ON)
add_compile_options(-fexceptions -sMODULARIZE=1 -sEXPORT_NAME=ovip)

swig_add_library(jsovip LANGUAGE javascript SOURCES 
javascript.i
../../src/comm/axi4_async.cpp
../../src/comm/axi4.cpp
../../src/comm/mem.cpp
)

# set buld output directory
set(XCOMM_LIB_DIR ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/../javascript/ovip)
set_target_properties(jsovip PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${SWIG_OUTFILE_DIR})
set_target_properties(jsovip PROPERTIES SUFFIX ".js")
set_property(TARGET jsovip PROPERTY SWIG_COMPILE_OPTIONS -napi)
target_link_libraries(jsovip emnapi xspcomm)

set(LK_OPS " -fexceptions -sMODULARIZE=1 -sEXPORT_NAME=ovip -sEXPORTED_FUNCTIONS=\"['_malloc','_free','_napi_register_wasm_v1','_node_api_module_get_api_version_v1']\"")
string(APPEND LK_OPS " --js-library=${NODE_MODULES_PATH}/emnapi/dist/library_napi.js")

target_link_options(jsovip PRIVATE "SHELL: ${LK_OPS}")

# copy file
set_source_files_properties(${SWIG_OUTFILE_DIR}/jsovip.js PROPERTIES GENERATED TRUE)
add_custom_command(
    OUTPUT ${XCOMM_LIB_DIR}/jsovip.so
    COMMAND ${CMAKE_COMMAND} -E copy
            ${SWIG_OUTFILE_DIR}/jsovip.js
            ${XCOMM_LIB_DIR}/jsovip.js
    COMMAND ${CMAKE_COMMAND} -E copy
            ${SWIG_OUTFILE_DIR}/jsovip.wasm
            ${XCOMM_LIB_DIR}/jsovip.wasm.${PROJECT_VERSION}
    DEPENDS jsovip
)

add_custom_command(
    OUTPUT jsovip_js_lnk
    COMMAND ${CMAKE_COMMAND} -E create_symlink
            "jsovip.wasm.${PROJECT_VERSION}"
            "jsovip.wasm"
    WORKING_DIRECTORY ${XCOMM_LIB_DIR}
    DEPENDS ${XCOMM_LIB_DIR}/jsovip.so
)

add_custom_target(
    _DummyTarget_create_jsovip_js_link ALL
  DEPENDS jsovip_js_lnk
)

install(DIRECTORY ${XCOMM_LIB_DIR} DESTINATION . USE_SOURCE_PERMISSIONS)
